package com.liuzh.websocket.controller;

import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.liuzh.websocket.service.LoginService;



@Controller
public class Login {
	@Autowired
	LoginService loginservice;
	
	@RequestMapping("/ws/loginvalidate")
	public String loginvalidate(@RequestParam("username") String username,@RequestParam("pic") String pic,@RequestParam("password") String pwd,HttpSession httpSession){
		String picode=(String) httpSession.getAttribute("rand");
		if(!picode.equalsIgnoreCase(pic))
			return "websocket/failcode";
		if(username==null)
			return "websocket/login";
		try {
			String realpwd=loginservice.getpwdbyname(username);
			if(realpwd!=null&&pwd.equals(realpwd))
			{
				long uid=loginservice.getUidbyname(username);
				httpSession.setAttribute("username", username);
				httpSession.setAttribute("uid", uid);
				return "websocket/chatroom";
			}else
				return "websocket/fail";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "websocket/fail";
	}
	
	@RequestMapping("/ws/login")
	public String login(){
		return "websocket/login";
	}
	
	@RequestMapping("/ws/logout")
	public String logout(HttpSession httpSession){
		httpSession.removeAttribute("username");
		httpSession.removeAttribute("uid");
		return "websocket/login";
	}
  }
